package com.fengye.fdfs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author fengyexjtu@126.com
 * @date 2022年05月22日 6:45 PM
 */
@RestController
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private FastdfsProperties fastdfsProperties;

    @PostMapping("upload")
    public Response<Object> upload(MultipartFile file) {
        try {
            File tempFile = null;
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String[] filename = originalFilename.split("\\.");
            tempFile = File.createTempFile(filename[0], filename[1]);
            file.transferTo(tempFile);
            String result = fileService.uploadFile(tempFile, file.getOriginalFilename());
            tempFile.deleteOnExit();
            log.info("上传成功, {}", result);
            String url = fastdfsProperties.getUrl() + result;
            return Response.OK("上传成功", url);
        } catch (IOException e) {
            throw new RuntimeException("上传失败:" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Response<Object> list(@RequestParam(name = "page", defaultValue = "1") int page,
                                 @RequestParam(name = "size", defaultValue = "10") int size) {
        if (page <= 1) {
            page = 1;
        }
        if (size <= 0) {
            size = 2;
        }
        page -= 1;

        Page<FileEntity> result = fileService.list(page, size);

        log.info("分页查询成功, {}", result);
        log.info("当前分页的数据为: {}", result.getContent());
        log.info("总条数: {}", result.getTotalElements());
        log.info("总分页数: {}", result.getTotalPages());
        log.info("是否为最后一页: {}", result.isLast());
        log.info("当前是第几页: {}", result.getNumber());
        log.info("分页大小: {}", result.getSize());
        log.info("本页有多少条数据: {}", result.getNumberOfElements());
        log.info("是否为第一页: {}", result.isFirst());
        log.info("是否为空: {}", result.isEmpty());
        return Response.OK("分页查询成功", result);
    }

    @PostMapping("/remove")
    public Response remove(@RequestParam String fileId) {
        if (!StringUtils.hasLength(fileId)) {
            return Response.error("删除文件失败,fileId=" + fileId);
        }
        int count = fileService.deleteFile(fileId);
        if (count > 0) {
            return Response.error("删除文件失败,fileId=" + fileId);
        }

        return Response.OK("删除文件成功", fileId);

    }
}
